package config

import (
	"strings"

	"github.com/spf13/viper"
)

type ContainerConfig struct {
	Mode          string `mapstructure:"mode"`
	InterfaceName string `mapstructure:"interface_name"`
	IpAddr        string `mapstructure:"ip_addr"`
}

type LogConfig struct {
	LogPath string `mapstructure:"path"`
}

type Config struct {
	Container ContainerConfig `mapstructure:"container"`
	Log       LogConfig       `mapstructure:"log"`
}

var AppConfig *Config

func LoadConfig(path string) {
	defaultConfig()
	viper.AddConfigPath(path)
	viper.SetConfigName("container")
	viper.SetConfigType("yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err.Error())
	}
	err = viper.Unmarshal(&AppConfig)
	if err != nil {
		panic(err.Error())
	}
	validConfig()
}

func defaultConfig() {
	viper.SetDefault("container.mode", "debug")
	viper.SetDefault("log.path", "./log")
}

func validConfig() {
	if AppConfig.Container.Mode != "debug" && AppConfig.Container.Mode != "test" && AppConfig.Container.Mode != "release" {
		panic("server mode must be debug, test or release")
	}
	if strings.TrimSpace(AppConfig.Container.InterfaceName) == "" {
		panic("interface name is empty")
	}
}
